
package com.ksd1.notes.markdown;

import java.util.ArrayList;
import java.util.List;

import com.ksd1.notes.markdown.parser.BoldParser;
import com.ksd1.notes.markdown.parser.CenterParser;
import com.ksd1.notes.markdown.parser.HeaderParser;
import com.ksd1.notes.markdown.parser.OrderListParser;
import com.ksd1.notes.markdown.parser.QuoteParser;
import com.ksd1.notes.markdown.parser.UnOrderListParser;
import com.ksd1.notes.markdown.Markdown.MDLine;
import com.ksd1.notes.markdown.Markdown.MDParser;
import com.ksd1.notes.markdown.Markdown.MDWord;


import android.text.SpannableStringBuilder;
import android.util.Log;

public class MDReader {

    private final String mContent;//需要格式化的内容
    private List<MDLine> mMDLines = new ArrayList<MDLine>();//保存文件的所有行
    private static List<MDParser> mMDParsers = new ArrayList<MDParser>();

    static {
        //格式化工具
        mMDParsers.add(new HeaderParser());//标题
        mMDParsers.add(new QuoteParser());//引用
        mMDParsers.add(new OrderListParser());//有序列表
        mMDParsers.add(new UnOrderListParser());//无序列表
        mMDParsers.add(new BoldParser());//加粗
        mMDParsers.add(new CenterParser());//居中
    }

    /**
     * 初始化mContent，并把所有行格式化后(parseLine)装载进mDLines
     * @param content 待格式化的内容
     */
    public MDReader(String content) {
        mContent = content;
        if (mContent == null || "".equals(content)) {
            return;
        }
        String[] lines = content.split("\n");
        for (String line : lines) {
            mMDLines.add(parseLine(line));//格式化后的行
        }
    }

    /**
     * @return content的标题（就是第一行）
     */
    public String getTitle() {
        if (mContent == null || "".equals(mContent)) {
            return "";
        }
        int end = mContent.indexOf("\n");
        return mContent.substring(0, end == -1 ? mContent.length() : end);
    }

    public String getContent() {
        return mContent;
    }

    public String getRawContent() {
        StringBuilder builder = new StringBuilder();
        for (MDLine line : mMDLines) {
            builder.append(line.getRawContent());
            builder.append("\n");
        }
        return builder.toString();
    }

    /**
     * @return 可以显示格式的文本(所有行拼接在一起)
     */
    public SpannableStringBuilder getFormattedContent() {
        return new MDFormatter(mMDLines).getFormattedContent();
    }


    /**
     * @param lineContent 待格式化的行
     * @return 格式化后的行 MDLine
     */
    private MDLine parseLine(String lineContent) {

        MDLine mdline = new MDLine(lineContent);
        if ("".equals(lineContent)) {
            return mdline;
        }

        String pContent = lineContent;

        //Parse the start format        
        for (MDParser parser : mMDParsers) { //用格式化工具一个一个进行格式
            MDWord word = parser.parseLineFmt(pContent);
            if (word.mFormat != Markdown.MD_FMT_TEXT) {//格式化成功
                mdline.mFormat = word.mFormat;
                pContent = lineContent.substring(word.mLength);//格式化内容为标记后开头到最后
                break;//行格式化只能符合一种
            }
        }

        //Parse the word format              
        StringBuilder mNoFmtContent = new StringBuilder();//不进行格式化的内容？

        while (pContent.length() != 0) {
            boolean isFmtFound = false;
            //Check format start with pContent
            for (MDParser parser : mMDParsers) {
                MDWord word = parser.parseWordFmt(pContent);//其实只有加粗/居中需要匹配


                if (word.mLength > 0) {//匹配
                    isFmtFound = true;
                    //Add no format string first 
                    int noFmtContentLen = mNoFmtContent.length();
                    if (noFmtContentLen != 0) {
                        mdline.mMDWords.add(new MDWord(mNoFmtContent.toString(), noFmtContentLen, Markdown.MD_FMT_TEXT));
                        mNoFmtContent = new StringBuilder();
                    }

                    mdline.mMDWords.add(word);//把需要格式化的词加入格式化词队列
                    pContent = pContent.substring(word.mLength);//后面的继续匹配
                    break;
                }
            }
            //If no format found, move to next position
            if (!isFmtFound) {
                mNoFmtContent.append(pContent.charAt(0));
                pContent = pContent.substring(1);

                if (pContent.length() == 0) {
                    mdline.mMDWords.add(new MDWord(mNoFmtContent.toString(), mNoFmtContent.length(), Markdown.MD_FMT_TEXT));
                    break;
                }
            }
        }
        return mdline;
    }

    protected void display() {
        StringBuilder builder = new StringBuilder();
        builder.append("Markdown Parse: \n" + mContent + "\n\n");
        for (MDLine line : mMDLines) {
            builder.append("Line format: " + line.mFormat + "\n");
            for (MDWord word : line.mMDWords) {
                builder.append("Word: " + word.mRawContent + ", " + word.mFormat + "\n");
            }
        }
        Log.d("JNote", builder.toString());
    }
}
